import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  { path: "/", redirect: "/home" },
  {
    path: "/home",
    name: "home",
    component: Home,
  },
  {
    path: "/free",
    name: "free",
    component: () => import(/* webpackChunkName: "free" */ "../views/Free.vue"),
  },
  {
    path: "/goods",
    name: "goods",
    component: () =>
      import(/* webpackChunkName: "goods" */ "../views/Goods.vue"),
  },
  {
    path: "/order",
    name: "order",
    component: () =>
      import(/* webpackChunkName: "order" */ "../views/Order.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () => import(/* webpackChunkName: "user" */ "../views/User.vue"),
    redirect: "/user/cart",
    children: [
      {
        path: "cart",
        component: () =>
          import(
            /* webpackChunkName: "user/cart" */ "../components/user/Cart.vue"
          ),
      },
    ],
    // //路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   //   //如果你准备去user页面
    //   let token = localStorage.getItem("x-auth-token");
    //   if (token) {
    //     //如果存在 正常进入user页面
    //     next();
    //   } else {
    //     //  否则提示未登录
    //     store.dispatch("toastShow/asyncChangeIsShowToast", {
    //       toastMsg: "你还没有登陆",
    //       toastType: "warning",
    //     });
    //   }
    // },
  },
  {
    path: "/details",
    name: "details",
    component: () =>
      import(/* webpackChunkName: "details" */ "../views/Details.vue"),
  },
  {
    //匹配所有地址，前面的所有地址没匹配上的话进入报错页面
    path: "*",
    component: () =>
      import(/* webpackChunkName: "error" */ "../views/Error.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
//解决重复点击一个路由报错问题（直接修改路由上的原型方法）
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};
//导航守卫
//全局的导航首位
//to:Router 即将要进入的目标
// from :Router 当前导航正要离开的路由
//next Function 一定要调用的方法，resolve 这个钩子
//每次路由发生切换都会触发
// router.beforeEach((to, from, next) => {
//   //如果你准备去user页面
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token");
//     if (token) {
//       //如果存在 正常进入user页面
//       next();
//     } else {
//       //  否则提示未登录
//       store.dispatch("toastShow/asyncChangeIsShowToast", {
//         toastMsg: "你还没有登陆",
//         toastType: "warning",
//       });
//     }
//     return; //预防代码继续执行下一个next()
//   }
//   next();
// });
export default router;
